/*************************************************************************
	> File Name: Sock.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/19 18:48
 ************************************************************************/

#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "Log.hpp"

class Sock
{
public:
    Sock (const uint16_t& port, const std::string& ip):_port(port), _ip(ip), _listensock(_Socket()) {}

    Sock () {}

    bool Bind()
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = inet_addr(_ip.c_str());
        return bind(_listensock, (struct sockaddr*)&server, sizeof server) == 0;
    }

    bool Connect()
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = inet_addr(_ip.c_str());
        return connect(_listensock, (struct sockaddr*)&server, sizeof server) == 0 ;
    }

    bool Listen()
    {
        return listen(_listensock, gbacklog) == 0;
    }

    bool Read(std::string& in)
    {
        char buffer[BUF_SIZE];
        memset(buffer, 0, sizeof buffer);
        ssize_t s = read(_listensock, buffer, sizeof buffer);
        in = std::string(buffer);
        return s != -1;
    }

    bool Write(const std::string& msg)
    {
        return write(_listensock, msg.c_str(), msg.size()) != -1;
    }

    int getSock()
    {
        return _listensock;
    }

    std::string getIp()
    {
        return _ip;
    }

    uint16_t getPort()
    {
        return _port;
    }

    ~Sock () 
    {
        if (_listensock >= 0) {
            close(_listensock);
        }
    }

protected:
    int _Socket()
    {
        int listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock < 0) {
            logMessage(FATAL, "socket errror, %d:%s", errno, strerror(errno));
            exit(1);
        }
        logMessage(NORMAL, "sock create success");
        return listensock;
    }

    uint16_t _port;
    std::string _ip;
    int _listensock;
    static const size_t BUF_SIZE = 8092;
    static const int gbacklog = 20;
};

class AcSock:protected Sock
{
public:
    AcSock (Sock sock) 
    {
        struct sockaddr_in src;
        memset(&src, 0, sizeof src);
        socklen_t len = sizeof src;
        _listensock = accept(sock.getSock(), (struct sockaddr*)&src, &len);
        _ip = inet_ntoa(src.sin_addr);
        _port = ntohs(src.sin_port);
    }
};
